import { createStore } from 'vuex';
import { login, getUser } from '@/api/user';
// import { resetRouter } from '@/router';
import {
  getToken,
  removeToken,
  setToken,
  getUserJson,
  setUser,
  removeUser,
} from '@/utils/auth';
const getDefaultState = () => {
  return {
    token: getToken(),
    user: getUserJson() || {},
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USER: (state, user) => {
    state.user = user;
  },
  SET_EMIL: (state, email) => {
    state.user.email = email;
  },
  SET_NAME: (state, nickName) => {
    state.user.nickName = nickName;
  },
  SET_USERID: (state, id) => {
    state.user.id = id;
  },
};
const actions = {
  // login
  login({ commit }, userinfo) {
    return new Promise((resolve, reject) => {
      console.log('login');
      login(userinfo)
        .then(
          (res) => {
            const { token } = res;
            commit('SET_TOKEN', token);
            setToken(token);
            resolve();
          },
          (err) => {
            reject(err);
          }
        )
        .catch((error) => {
          reject(error);
        });
    });
  },

  getUser({ commit }) {
    return new Promise((resolve, reject) => {
      getUser()
        .then((response) => {
          if (!response) {
            return reject(
              new Error('Verification failed, please Login again.')
            );
          }
          commit('SET_USER', response);
          setUser(response);
          resolve(response);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // resetToken
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit('RESET_STATE');
      resolve();
    });
  },
  logout({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      removeUser(); // must remove  token  first
      // resetRouter();
      commit('RESET_STATE');
      resolve();
    });
  },
};

const getters = {
  token: (state) => state.token,
  id: (state) => state.user._id,
  column: (state) => state.user.column,
  nickName: (state) => state.user.nickName,
};
export default createStore({
  state,
  mutations,
  actions,
  getters,
  modules: {},
  // strict: true
});
